package com.yhw.srb.sms.controller.api;

import com.yhw.common.exception.Assert;
import com.yhw.common.result.R;
import com.yhw.common.result.ResponseEnum;
import com.yhw.common.util.RandomUtils;
import com.yhw.common.util.RegexValidateUtils;
import com.yhw.srb.sms.client.CoreUserInfoClient;
import com.yhw.srb.sms.service.SmsService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

@Api(tags = "短信管理")
@RestController
@RequestMapping("/api/sms/")
//@CrossOrigin
@Slf4j
public class ApiSmsController {

    @Resource
    private SmsService smsService;

    @Resource
    private CoreUserInfoClient coreUserInfoClient;

    @Resource
    private RedisTemplate redisTemplate;

    @ApiOperation("获取验证码")
    @GetMapping("/send/{mobile}")
    public R send(@ApiParam(value = "手机号",required = true) @PathVariable("mobile") String mobile){

        //MOBILE_NULL_ERROR(-202, "手机号不能为空"),
        Assert.notEmpty(mobile, ResponseEnum.MOBILE_NULL_ERROR);
        //MOBILE_ERROR(-203, "手机号不正确"),
        boolean checkCellphone = RegexValidateUtils.checkCellphone(mobile);
        Assert.isTrue(checkCellphone, ResponseEnum.MOBILE_ERROR);


        //手机号是否注册
        Boolean result = coreUserInfoClient.checkMobile(mobile);
        System.out.println("result="+result);
        Assert.isTrue(result==false,ResponseEnum.MOBILE_EXIST_ERROR);

        // 模板几
        String templateId = "1";

        // 生成验证码
        String code = RandomUtils.getFourBitRandom();
        System.out.println(code);
        // 有效时间
        int time = 10;
        // code 要发的验证码     time 多少分钟内有效
        String[] datas = {code,""+time};

        // 发送短信
        smsService.send(mobile,templateId,datas);

        // 将验证码存入redis
        redisTemplate.opsForValue().set("srb:sms:code:"+mobile,code,time, TimeUnit.MINUTES);

        return R.ok().message("短信发送成功");
    }

}
